package com.zsc.shixun.controller;

import com.zsc.shixun.common.CommonResult;
import com.zsc.shixun.common.ResultCode;
import com.zsc.shixun.common.ResultUtil;
import com.zsc.shixun.config.UserSecurity;
import com.zsc.shixun.contant.Contant;
import com.zsc.shixun.entity.User;
import com.zsc.shixun.exception.ApiException;
import com.zsc.shixun.model.unauthorize.PasswordVO;
import com.zsc.shixun.model.unauthorize.UserRegisterVO;
import com.zsc.shixun.service.IArticleService;
import com.zsc.shixun.service.IUserService;
import com.zsc.shixun.service.function.ArticleCommentCollectService;
import com.zsc.shixun.service.function.BloggerService;
import com.zsc.shixun.service.function.IndexService;
import com.zsc.shixun.utils.LoginMessageUtils;
import com.zsc.shixun.utils.ProducerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 不用授权
 * </p>
 *
 * @author ZWYZY
 * @since 2020/6/7
 */
@Validated
@Controller
@RequestMapping("/unAuthorize")
public class UnAuthorizeController {
    private static final Logger logger = LoggerFactory.getLogger(UnAuthorizeController.class);
    @Autowired
    public IUserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ProducerUtils producerUtils;
    @Autowired
    private LoginMessageUtils loginMessageUtils;
    @Autowired
    private IndexService indexService;
    @Autowired
    private BloggerService bloggerService;
    @Autowired
    private ArticleCommentCollectService articleCommentCollectService;

    @Autowired
    private IArticleService articleService;

    /**
     * 登录跳转
     *
     * @param request
     * @param map
     * @return
     */
    @RequestMapping("/login")
    public String login(HttpServletRequest request, Map map) {
        // 分别获取请求头和参数url中的原始访问路径
        String referer = request.getHeader("Referer");
        String url = request.getParameter("url");
        System.out.println("referer= " + referer);
        System.out.println("url= " + url);

        // 如果参数url中已经封装了原始页面路径，直接返回该路径
        if (url != null && !url.equals("")) {
            map.put("url", url);
            // 如果请求头本身包含登录，将重定向url设为空，让后台通过用户角色进行选择跳转
        } else if (referer != null && referer.contains("/login")) {
            map.put("url", "");
        } else {
            // 否则的话，就记住请求头中的原始访问路径
            map.put("url", referer);
        }
        return "unauthorize/login";
    }

    /**
     * 博客页跳转
     *
     * @return
     */
    @RequestMapping({"/index", "/"})
    public String index() {
        return "unauthorize/index";
    }

    /**
     * 注册页面跳转
     *
     * @return
     */
    @RequestMapping("/toregister")
    public String toregister() {
        return "unauthorize/register";
    }

    /**
     * 忘记密码页跳转
     *
     * @return
     */
    @RequestMapping("/toforgetpassword")
    public String toforgetpassword() {
        return "unauthorize/forgetpassword";
    }

    /**
     * 博主页跳转--
     *
     * @return
     * @Param id 博主id
     */
    @RequestMapping("/blogger")
    public String blogger(HttpServletRequest request, @RequestParam(required = false) Long id) {
        if (id != null) {
            request.setAttribute("id", id);
        }
        return "unauthorize/blogger";
    }

    /**
     * 文章页跳转
     *
     * @return
     */
    @RequestMapping("/article")
    public String article(HttpServletRequest request, @RequestParam(required = false) Long id) {
        return "unauthorize/article";
    }

    /**
     * 修改密码页跳转
     *
     * @param
     * @return
     */
    @GetMapping("/torecoverpassword")
    public String recoverpassword(HttpServletRequest request, @RequestParam(required = false) Long uid) {
        if (uid != null) {
            logger.info("通过找回密码得到的uid");
            request.setAttribute("uid", uid.toString());
        } else {

            UserSecurity principal = loginMessageUtils.getMessage();
            Long id = principal.getLoginUser().getId();
            logger.info("通过更改密码找回的uid");
            request.setAttribute("uid", id.toString());
        }
        return "unauthorize/recoverpassword";
    }

    @GetMapping("/isLogin")
    @ResponseBody
    public CommonResult isLogin(){
        return ResultUtil.success(loginMessageUtils.isLogin());
    }

    /**
     * 注册
     *
     * @param userRegisterVO
     * @return
     */
    @PostMapping(value = "/register")
    @ResponseBody
    public Object register(@Validated @ModelAttribute UserRegisterVO userRegisterVO) {
        if (!redisTemplate.hasKey(Contant.REGISTER_CODE_KEY + userRegisterVO.getEmail())) {
            return new CommonResult(ResultCode.CODE_NULL);
        }
        Object rawcode = redisTemplate.opsForValue().get(Contant.REGISTER_CODE_KEY + userRegisterVO.getEmail());

        if (rawcode.equals(userRegisterVO.getCode())) {
            logger.info("验证码正确");
            redisTemplate.delete(Contant.REGISTER_CODE_KEY + userRegisterVO.getEmail());
            User user = userService.findByEmail(userRegisterVO.getEmail());
            if (user != null) {
                throw new ApiException(ResultCode.USER_HAS_EXIST);
            }
            System.out.println(userRegisterVO);
            Object o = userService.register(userRegisterVO);
            return ResultUtil.success(o);
        } else {
            logger.info("验证码错误");
            return new CommonResult(ResultCode.CODE_ERROR);
        }

    }

    /**
     * 注册发送验证码
     *
     * @param email
     * @return
     */
    @GetMapping("/register/sendCode")
    @ResponseBody
    public CommonResult sendCodeByRegister(
            HttpServletRequest request,
            @NotNull(message = "邮箱不能为空") @Email(message = "不符合邮箱规则") @RequestParam(required = false) String email) {
        if (userService.findByEmail(email) != null) {
            throw new ApiException(ResultCode.USER_HAS_EXIST);
        }
        String code = generateCode();
        logger.info("邮箱为：" + email + ",生成的验证码为：" + code);
        redisTemplate.opsForValue().set(Contant.REGISTER_CODE_KEY + email, code, 60, TimeUnit.SECONDS);
        producerUtils.sendCode(email, "it技术博客管理系统-注册账号确认", code);
        logger.info("发送验证码成功");
        return ResultUtil.success("验证码已发送到您的邮箱");
    }

    /**
     * 发送验证码
     *
     * @param email
     * @return
     */
    @GetMapping("/sendCode")
    @ResponseBody
    public CommonResult sendCode(
            HttpServletRequest request,
            @NotNull(message = "邮箱不能为空") @Email(message = "不符合邮箱规则") @RequestParam(required = false) String email) {
        if (userService.findByEmail(email) == null) {
            throw new ApiException(ResultCode.EMAIL_NOT_FOUND);
        }
        String code = generateCode();
        logger.info("邮箱为：" + email + ",生成的验证码为：" + code);
        redisTemplate.opsForValue().set(Contant.FORGET_PASSWORD_CODE_KEY + email, code, 60, TimeUnit.SECONDS);
        producerUtils.sendCode(email, "it技术博客管理系统-找回密码确认", code);
        logger.info("发送验证码成功");
        return ResultUtil.success("验证码已发送到您的邮箱");
    }

    /**
     * 验证码验证
     *
     * @param
     * @return
     */
    @GetMapping("/validCode")
    @ResponseBody
    public CommonResult validCode(
            @NotNull(message = "邮箱不能为空") @Email(message = "不符合邮箱规则") @RequestParam(value = "email", required = false) String email,
            @NotNull(message = "验证码不能为空") @RequestParam(value = "code", required = false) String code
    ) {
        if (!redisTemplate.hasKey(Contant.FORGET_PASSWORD_CODE_KEY + email)) {
            return new CommonResult(ResultCode.CODE_NULL);
        }

        Object rawcode = redisTemplate.opsForValue().get(Contant.FORGET_PASSWORD_CODE_KEY + email);
        if (rawcode.equals(code)) {
            logger.info("验证码正确");
            redisTemplate.delete(Contant.FORGET_PASSWORD_CODE_KEY + email);
            User user = userService.findByEmail(email);
            if (user == null) {
                throw new ApiException(ResultCode.EMAIL_NOT_FOUND);
            }
            return ResultUtil.success(user.getId());
        } else {
            logger.info("验证码错误");
            return new CommonResult(ResultCode.CODE_ERROR);
        }

    }

    /**
     * 随机生成6位验证码
     *
     * @return
     */
    public String generateCode() {
        //
        //RandomString.make(6);
        Random random = new Random();
        int s = random.nextInt(899999);
        return String.valueOf(s + 100000);
    }

    /**
     * 根据id更换密码
     *
     * @return
     */
    @PostMapping("/updatePassword")
    @ResponseBody
//    @Secured(value = "ROLE_user")
    public CommonResult updatePassword(@Validated @ModelAttribute PasswordVO passwordVO
    ) {
        userService.updatePassword(passwordVO.getPassword(), Long.parseLong(passwordVO.getUid()));
        return ResultUtil.success("修改密码成功");
    }


    /**
     * 博客园----文章列表
     *
     * @return
     */
    @GetMapping("/getArticleList")
    @ResponseBody
    public CommonResult getArticleList() {

        return ResultUtil.success(indexService.getArticleList());
    }

    /**
     * 博客园-----排行榜top10
     *
     * @return
     */
    @GetMapping("/getTop10")
    @ResponseBody
    public CommonResult getTop10() {

        return ResultUtil.success(indexService.getTop10());
    }

    /**
     * 博客页----公告栏
     *
     * @return
     */
    @GetMapping("/getNotice")
    @ResponseBody
    public CommonResult getNotice() {
        return ResultUtil.success(indexService.getNotice());
    }

    /**
     * 博主页信息
     *
     * @param id
     * @return
     */
    @GetMapping("/getBlogger")
    @ResponseBody
    public CommonResult getBlogger(@NotNull(message = "id不能为空") @RequestParam(required = false) Long id) {

        return ResultUtil.success(bloggerService.getBlogger(id));
    }

    /**
     * 刷新功能，删除缓存
     *
     * @return
     */
    @GetMapping("/deleteAllCache")
    @ResponseBody
    public CommonResult deleteAllCache() {
        redisTemplate.delete(redisTemplate.keys("*"));
        logger.info("-------------------删除所有缓存成功-----------------------");
        return ResultUtil.success("缓存删除成功了，亲");
    }

    /**
     * 获取文章页数据
     *
     * @param id
     * @return
     */
    @GetMapping("/getArticle")
    @ResponseBody
    public CommonResult getArticle(@NotNull(message = "id不能为空") @RequestParam(required = false) Long id) {
        redisTemplate.delete(redisTemplate.keys("*"));
        return ResultUtil.success(articleCommentCollectService.getArticle(id));
    }
//    @GetMapping("/search")
//
//    public String search(@RequestParam(required = false) String keyword){
//
//    }
}
